#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<unistd.h>
#include<time.h>
#include<mysql/mysql.h>
#include<time.h>
int handData(char *buf,int confd)
{
	char type[3];
	memset(type,0,3);
	printf("buf=%s\n",buf);
	strncpy(type,buf+1,2);//#01|andy|123
	MYSQL mysql;
	MYSQL_RES *result=NULL;
	MYSQL_ROW row;
	mysql_init(&mysql);
	if(mysql_real_connect(&mysql,"127.0.0.1","root","shenboyuan","qq",0,NULL,0)==NULL)
	{
		printf("connect error\n");
		return -1;
	}//xuyaogenjufanhuizhishifoushinullzhizhenlaipanduanshifoulianjiechengong
	printf("type=%s\n",type);
	type[2]='\0';

	if(strcmp(type,"01")==0)//zhuce
	{
		char uName[32];
		char pWord[32];
		sscanf(buf+4,"%[^|]|%s",uName,pWord);
		char sqlStr[1024]={0};
		sprintf(sqlStr,"select * from UserTb where UserName='%s'",uName);
		//printf("%s\n",sqlStr);
		if(mysql_query(&mysql,sqlStr)!=0)
        	{
            	printf("select error:%s\n",mysql_error(&mysql));
            	return -1;
        	}
		result=mysql_store_result(&mysql);
		row=mysql_fetch_row(result);
		if(row)
		{
			write(confd,"#01|1|UserExist",15);
		}
		else
		{
			write(confd,"#01|0|RegSuccess",16);
			sprintf(sqlStr,"insert into UserTb values('%s','%s',0,-1)",uName,pWord);
			if(mysql_query(&mysql,sqlStr)!=0)
        		{
            		printf("insert error:%s\n",mysql_error(&mysql));
            		return -1;
        		}
		}
	}
	if(strcmp(type,"02")==0)
	{
		printf("m2success\n");
		char uName[32];
		char pWord[32];
		sscanf(buf+4,"%[^|]|%s",uName,pWord);
                char sqlStr[1024]={0};
		sprintf(sqlStr,"select * from UserTb where UserName='%s' and password='%s'",uName,pWord);
		if(mysql_query(&mysql,sqlStr)!=0)
		{
			printf("#02:%s\n",mysql_error(&mysql));
		}
		result=mysql_store_result(&mysql);
		row=mysql_fetch_row(result);
		printf("#02.1success\n");
		if(row)
		{
			write(confd,"#02|0|LoginSuccess",18);
			sprintf(sqlStr,"update UserTb set OnlineFlag=1, confd='%d' where UserName='%s'",confd,uName);
			printf("%s\n",sqlStr);
			if(mysql_query(&mysql,sqlStr)!=0)
				printf("#02updateerror:%s\n",mysql_error(&mysql));
			sprintf(sqlStr,"select Sender,SendTime,Message  from MessageTb where Recept='%s' and SendFlag=0 order by SendTime",uName);
			printf("%s\n",sqlStr);
			if(mysql_query(&mysql,sqlStr)!=0)
				printf("%s\n",mysql_error(&mysql));
			result=mysql_store_result(&mysql);
			int temp=0;
			while((row=mysql_fetch_row(result))!=NULL)//#
			{
				temp++;
				char message[1024];
				message[0]='*';
				message[1]='\0';
				strcat(message,*row);
				strcat(message,"|");
				strcat(message,*(row+1));
				strcat(message,"|");
				strcat(message,*(row+2));
				printf("row=%ld,row+1=%ld,row+2=%ld\n",strlen(*row),strlen(*(row+1)),strlen(*(row+2)));
				printf("message=%s\n",message);
				printf("write=%ld\n",write(confd,message,strlen(message)));
				printf("yes\n");
			}
			sprintf(sqlStr,"update MessageTb set SendFlag=1 where Recept='%s' and SendFlag=0",uName);
                        printf("%s\n",sqlStr);
			if(mysql_query(&mysql,sqlStr)!=0)
                                printf("%s\n",mysql_error(&mysql));
		}
		else
		{
			write(confd,"#02|1|LoginError",16);
		}
	}
	if(strcmp(type,"03")==0)//#03|Sender|Recept|txt
    {
        char sendUser[32]={0};
        char txt[32]={0};
        char message[1024]={0};
        char User[32]={0};
        sscanf(buf+4,"%[^|]|%[^|]|%s",User,sendUser,txt);
        printf("User=%s\n",User);
        printf("sendUser=%s\n",sendUser);
        printf("txt=%s\n",txt);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select confd,OnlineFlag from UserTb where UserName='%s'",sendUser);
        
         
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("select error:%s\n",mysql_error(&mysql));
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
            int userconfd=atoi(*row);
            int onlineflag=atoi(*(row+1));
            printf("userconfd=%s\n",*row);
		time_t now=time(NULL);
			char timeStr[32]={0};
            strftime(timeStr,sizeof(timeStr),"%Y-%m-%d %H:%M:%S",localtime(&now));
            if(onlineflag)
            {
            	sprintf(sqlStr,"insert into MessageTb values('%s','%s','%s',1,'%s')",User,sendUser,timeStr,txt);
            	if(mysql_query(&mysql,sqlStr)!=0)
        		{
            		printf("insert error:%s\n",mysql_error(&mysql));
            		return -1;
        		}
            	sprintf(message,"*%s|%s|%s",User,timeStr,txt);
            	write(userconfd,message,sizeof(message));
            }
            else
            {
            	sprintf(sqlStr,"insert into MessageTb values('%s','%s','%s',0,'%s')",User,sendUser,timeStr,txt);
            	if(mysql_query(&mysql,sqlStr)!=0)
        		{
            		printf("insert error:%s\n",mysql_error(&mysql));
            		return -1;
        		}
            }
        }
        else
        {
        	write(confd,"#03|empty user\n",15);
            printf("%s has no confd\n",sendUser);
        }
        printf("sqlStr=%s\n",sqlStr);
    }
    if(strcmp(type,"04")==0)//#04|Sender|Recept
    {
    	char Sender[32]={0};
        char message[1024]={0};
        char Recept[32]={0};
        sscanf(buf+4,"%[^|]|%s",Sender,Recept);
        printf("Sender=%s\n",Sender);
        printf("Recept=%s\n",Recept);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select * from UserTb where UserName='%s'",Recept);
        printf("sqlStr=%s\n",sqlStr);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("select error:%s\n",mysql_error(&mysql));
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
        	int userconfd=atoi(*(row+3));
        	int OnlineFlag=atoi(*(row+2));
        	sprintf(sqlStr,"select * from FriendTb where friend_1='%s' and friend_2='%s'",Sender,Recept);
        	printf("sqlStr=%s\n",sqlStr);
        	if(mysql_query(&mysql,sqlStr)!=0)
        	{
            	printf("select error:%s\n",mysql_error(&mysql));
            	return -1;
        	}
        	result=mysql_store_result(&mysql);
        	if(result==NULL)
        	{
            	printf("result error:%s\n",mysql_error(&mysql));
            	return -1;
        	}
        	row=mysql_fetch_row(result);
        	if(row)
        		write(confd,"ExistFriend\n",12);
        	else
        	{
        		sprintf(sqlStr,"insert into AddFriendTb values('%s','%s',0)",Sender,Recept);
            		if(mysql_query(&mysql,sqlStr)!=0)
        		{
            			printf("insert error:%s\n",mysql_error(&mysql));
            			return -1;
        		}
        		if(OnlineFlag)
        		{
            			sprintf(message,"#04|%s",Sender);
            			write(userconfd,message,sizeof(message));
        		}
        	}
        }
        else
        {
        	write(confd,"#04|empty user\n",15);
        }
    }
	mysql_free_result(result);
	mysql_close(&mysql);
	printf("%s\n",buf);
	return 1;

}
int offOnline(int confd)
{
	MYSQL mysql;
        mysql_init(&mysql);
        mysql_real_connect(&mysql,"127.0.0.1","root","shenboyuan","qq",0,NULL,0);
	char sqlStr[1024]={0};
	sprintf(sqlStr,"update UserTb set OnlineFlag=0 ,confd=-1 where confd='%d'",confd);
        if(mysql_query(&mysql,sqlStr)!=0)
		printf("offOnlineError:%s\n",mysql_error(&mysql));
	mysql_close(&mysql);
	printf("offline\n");
}
int main()
{
	int lisfd=socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in sevaddr;
	sevaddr.sin_family=AF_INET;
	sevaddr.sin_port=htons(9988);
	sevaddr.sin_addr.s_addr=inet_addr("192.168.164.128");


	int maxfd=0;
	fd_set allset,reset;
	FD_ZERO(&allset);
	int clifd[1024]={0};
	memset(clifd,-1,sizeof(clifd));
	int confd=0;
	int curi=0,i=0;

	if(bind(lisfd,(struct sockaddr*)&sevaddr,sizeof(sevaddr))!=0)
	{
		printf("binderror\n");
		return -1;
	}
	listen(lisfd,3);


	FD_SET(lisfd,&allset);
	if(maxfd<lisfd)
		maxfd=lisfd;
	
	while(1)
	{
		reset=allset;
		int nready=select(maxfd+1,&reset,NULL,NULL,NULL);
		if(nready<=0)
		{
			printf("select error\n");
			return -1;
		}
		if(FD_ISSET(lisfd,&reset))
		{
			 confd=accept(lisfd,NULL,NULL);
			printf("confd=%d\n",confd);
			if(confd==-1)
			{
				printf("accept error\n");
				return -1;
			}
			FD_SET(confd,&allset);
			if(confd>maxfd)
				maxfd=confd;
			for(i=0;i<curi;i++)
			{
				if(clifd[i]==-1)
				{
					clifd[i]=confd;
					break;
				}
			}
			if(curi==i)
			{
				if(curi==1024)
				{
					printf("max fd\n");
					return -1;
				}
				else
					clifd[curi++]=confd;
			}
		}
		for(i=0;i<curi;i++)
		{
			char sqlStr[1024];
			confd=clifd[i];
			if(FD_ISSET(confd,&reset))
			{
				char buf[1024]={0};

				if(read(confd,buf,sizeof(buf))==0)
				{
					clifd[i]=-1;
					offOnline(confd);
					continue;
				}
				handData(buf,confd);
				//write(confd,"yes",3);
			}
		}
	}
}
